package;

import board.Casillero;
import board.Dice;
import board.Roulette;
import board.Team;
import flixel.FlxG;
import flixel.FlxObject;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.group.FlxGroup;
import flixel.system.FlxSound;
import flixel.text.FlxText;
import flixel.tweens.FlxTween;
import flixel.ui.FlxButton;
import flixel.util.FlxColor;
import flixel.util.FlxMath;
import flixel.tweens.FlxEase;
import flixel.util.FlxPoint;
import flixel.input.gamepad.FlxGamepad;
import sys.db.Connection;
import sys.db.SqLite;

import flixel.input.gamepad.LogitechButtonID;

/**
 * A FlxState which can be used for the actual gameplay.
 */
class TableroTestState extends FlxState
{
	var team1 : Team;
	var team2 : Team;
	var team3 : Team;
	var team4 : Team;
	private var paused:Bool;
	private var spinTime:Float;
	private var score1:FlxText;
	private var score2:FlxText;
	private var score3:FlxText;
	private var score4:FlxText;
	private var scoreText:FlxText;
	private var estado:String;
	private var timeToRoll:Float;
	private var timeToSpin:Float;
	private var timeToFade:Float;
	private var currentTeam:Team;
	private var movesLeft:Int;
	private var modeName:FlxText;
	private var passGo:Bool;
	private var rondaText:FlxText;
	private var dundundun:FlxSound;
	private var ruletaSound:FlxSound;
	private var ruletaFinSound:FlxSound;
	private var fichaSound:FlxSound;
	private var dadoSound:FlxSound;
	private var pausedText:FlxText;
	var dice : Dice;
	var ruleta:Roulette;
	var bg:FlxSprite;
	private var rolling:Bool;
	public static var casilleros:Array<Casillero>;
	/**
	 * Function that is called up when to state is created to set it up. 
	 */
	override public function create():Void
	{
		// Creamos casilleros y los añadimos al juego
		
		passGo = false;
		FlxG.camera.fade(FlxColor.BLACK,1,true,fadeIn);
		
		casilleros = new Array();
		super.create();
		dundundun = new FlxSound();
		dundundun.loadEmbedded("assets/sounds/dundundun.wav");
		
		ruletaSound = new FlxSound();
		ruletaSound.loadEmbedded("assets/sounds/ruleta.wav");
		
		fichaSound = new FlxSound();
		fichaSound.loadEmbedded("assets/sounds/ficha.wav");
		
		spinTime = 5;
		ruletaFinSound = new FlxSound();
		ruletaFinSound.loadEmbedded("assets/sounds/ruletaFin.wav");
		
		var cnx = sys.db.Sqlite.open("assets/TestDB.sqlite");
		var rset = cnx.request("SELECT * FROM Partidas");
		for ( row in rset ) {
			Reg.score1 = row.score1;
			Reg.score2 = row.score2;
			Reg.score3 = row.score3;
			Reg.score4 = row.score4;
			Reg.carcel1 = row.carcel1;
			Reg.carcel2 = row.carcel2;
			Reg.carcel3 = row.carcel3;
			Reg.carcel4 = row.carcel4;
			Reg.multiplier1 = row.multiplier1;
			Reg.multiplier2 = row.multiplier2;
			Reg.multiplier3 = row.multiplier3;
			Reg.multiplier4 = row.multiplier4;
			Reg.position1 = row.posicion1;
			Reg.position2 = row.posicion2;
			Reg.position3 = row.posicion3;
			Reg.position4 = row.posicion4;
			Reg.rondas = row.rondas;
		}
		var rset = cnx.request("SELECT * FROM ScoreAdd");
		for ( row in rset ) {
			Reg.scoreAdd1 = row.add1;
			Reg.scoreAdd2 = row.add2;
			Reg.scoreAdd3 = row.add3;
			Reg.scoreAdd4 = row.add4;
		}
		cnx.close();
		var casillero:Casillero;
		paused = false;
		casillero = new Casillero(0, "Salida");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(1, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(2, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(3, "Dado");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(4, "Rojo");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(5, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(6, "MultX2");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(7, "Rojo");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(8, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(9, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(10, "Carcel");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(11, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(12, "Rojo");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(13, "Dado");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(14, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(15, "Rojo");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(16, "MultX2");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(17, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(18, "Verde");
		add(casillero);
		casilleros.push(casillero);
		casillero = new Casillero(19, "Rojo");
		add(casillero);
		casilleros.push(casillero);
		bg = new FlxSprite(0, 0);
		bg.loadGraphic("assets/images/fondo.png");
		add(bg);
		/*
		for (i in 0...20) 
		{
			var casillero:Casillero = new Casillero(i);
			add(casillero);
			casilleros.push(casillero);
		}
		*/
		// Creamos equipos y los añadimos al juego
		score1 = new FlxText(200, 150, 200, "0", 30);
		score1.setFormat(null, 40, FlxColor.BLUE, "left", FlxText.BORDER_OUTLINE);
		score1.font = "font";
		add(score1);
		score2 = new FlxText(600, 150, 200, "0", 30);
		score2.setFormat(null,40,FlxColor.RED,"left",FlxText.BORDER_OUTLINE);
		score2.font = "font";
		add(score2);
		score3 = new FlxText(200, 350, 200, "0", 30);
		score3.setFormat(null,40,FlxColor.GREEN,"left",FlxText.BORDER_OUTLINE);
		score3.font = "font";
		add(score3);
		score4 = new FlxText(600, 350, 200, "0", 30);
		score4.setFormat(null,40,FlxColor.YELLOW,"left",FlxText.BORDER_OUTLINE);
		score4.font = "font";
		add(score4);
		team1 = new Team(FlxColor.BLUE, 0,score1,Reg.score1,Reg.position1,"assets/images/equipo1.png");
		team2 = new Team(FlxColor.RED, 1,score2,Reg.score2,Reg.position2,"assets/images/equipo2.png");
		team3 = new Team(FlxColor.GREEN, 2,score3,Reg.score3,Reg.position3,"assets/images/equipo3.png");
		team4 = new Team(FlxColor.YELLOW, 3, score4, Reg.score4, Reg.position4, "assets/images/equipo4.png");
		team1.carcel = Reg.carcel1;
		team2.carcel = Reg.carcel2;
		team3.carcel = Reg.carcel3;
		team4.carcel = Reg.carcel4;
		score1.text = Std.string(Reg.score1);
		score1.text = Std.string(Reg.score1);
		score2.text = Std.string(Reg.score2);
		score3.text = Std.string(Reg.score3);
		score4.text = Std.string(Reg.score4);
		add(team1);
		add(team2);
		add(team3);
		add(team4);
		
		dice = new Dice(FlxG.width / 2 - 130/2, FlxG.height / 2 - 150/2);
		add(dice);
		
		rolling = false;
		currentTeam = team1;
		estado = "nada";
		timeToRoll = 1;
		timeToSpin = 1;
		
		ruleta = new Roulette();
		ruleta.disc.x = FlxG.width / 2 - ruleta.disc.width / 2;
		ruleta.disc.y = FlxG.height / 2 - ruleta.disc.height / 2;
		ruleta.disc.scale.set(0, 0);
		ruleta.arrow.scale.set(0, 0);
		ruleta.disc.angle = Reg.angle;
		add(ruleta);
		
		scoreText = new FlxText( -100, -100, 200, "+3", 30);
		scoreText.setFormat(null, 40, FlxColor.GREEN, "left", FlxText.BORDER_OUTLINE);
		scoreText.font = "font";
		add(scoreText);
		
		modeName = new FlxText(FlxG.width / 2 - 400, FlxG.height / 2, 800,"NORMAL", 80);
		modeName.setFormat(null, 80, FlxColor.WHITE, "center", FlxText.BORDER_OUTLINE);
		modeName.font = "font";
		modeName.y -= modeName.height / 2;
		modeName.scale.set(0,0);
		add(modeName);
		
		timeToFade = 0.6;
	
		pausedText = new FlxText(0, FlxG.height / 2 - 100, 800, "PAUSA");
		pausedText.setFormat("title", 120, FlxColor.ROYAL_BLUE, "center", FlxText.BORDER_OUTLINE);
		pausedText.visible = false;
		add(pausedText);
	}
	
	/**
	 * Function that is called when this state is destroyed - you might want to 
	 * consider setting all objects this state uses to null to help garbage collection.
	 */
	override public function destroy():Void
	{
		super.destroy();
	}

	private function fadeIn():Void
	{
		if (Reg.rondas % 5 == 0)
		{
			dundundun.play();
			rondaText = new FlxText(0, FlxG.height / 2 - 100, 800, "QUEDAN " + Reg.rondas + " RONDAS!");
			rondaText.setFormat("title", 120, FlxColor.ROYAL_BLUE, "center", FlxText.BORDER_OUTLINE);
			rondaText.scale.set(0, 0);
			add(rondaText);
			if (Reg.rondas == 0)
				rondaText.text = "ULTIMA RONDA!";
			var tween = FlxTween.tween(rondaText.scale,{x:1,y:1},1,{complete:rondaTween,ease:FlxEase.bounceOut});
		}
		else
			estado = "adding";
	}
	private function rondaTween(tween:FlxTween):Void
	{
		estado = "adding";
		var tween = FlxTween.tween(rondaText,{alpha:0},3);
	}
	
	/**
	 * Function that is called once every frame.
	 */
	
	private function addScore1(tween:FlxTween):Void
	{

	}
	
	private function finSuma(tween:FlxTween):Void
	{
		estado = "adding";
	}
	 
	override public function update():Void
	{
		if (FlxG.keys.justPressed.P)
		{
			pausedText.visible = !pausedText.visible;
			paused = !paused;
		}
		if (paused)
			return;
		
		super.update();
			
		switch (estado)
		{
			case "adding":
				if (Reg.scoreAdd1 != 0)
				{
					team1.addScore(Reg.scoreAdd1);
					scoreText.color = FlxColor.GREEN;
					scoreText.text = "+" + Std.string(Reg.scoreAdd1);
					scoreText.alpha = 1;
					scoreText.x = team1.scoreText.x;
					scoreText.y = team1.scoreText.y;
					var tween = FlxTween.tween(scoreText, { y:scoreText.y - 50, alpha:0 }, 0.5, { complete:finSuma } );
					estado = "nada";
					Reg.scoreAdd1 = 0;
				}
				else if (Reg.scoreAdd2 != 0)
				{
					team2.addScore(Reg.scoreAdd2);
					scoreText.color = FlxColor.GREEN;
					scoreText.text = "+" + Std.string(Reg.scoreAdd2);
					scoreText.alpha = 1;
					scoreText.x = team2.scoreText.x;
					scoreText.y = team2.scoreText.y;
					var tween = FlxTween.tween(scoreText, { y:scoreText.y - 50, alpha:0 }, 0.5, { complete:finSuma } );
					estado = "nada";
					Reg.scoreAdd2 = 0;
				}
				else if (Reg.scoreAdd3 != 0)
				{
					team3.addScore(Reg.scoreAdd3);
					scoreText.color = FlxColor.GREEN;
					scoreText.text = "+" + Std.string(Reg.scoreAdd3);
					scoreText.alpha = 1;
					scoreText.x = team3.scoreText.x;
					scoreText.y = team3.scoreText.y;
					var tween = FlxTween.tween(scoreText, { y:scoreText.y - 50, alpha:0 }, 0.5, { complete:finSuma } );
					estado = "nada";
					Reg.scoreAdd3 = 0;
				}
				else if (Reg.scoreAdd4 != 0)
				{
					team4.addScore(Reg.scoreAdd4);
					scoreText.color = FlxColor.GREEN;
					scoreText.text = "+" + Std.string(Reg.scoreAdd4);
					scoreText.alpha = 1;
					scoreText.x = team4.scoreText.x;
					scoreText.y = team4.scoreText.y;
					var tween = FlxTween.tween(scoreText, { y:scoreText.y - 50, alpha:0 }, 0.5, { complete:finSuma } );
					estado = "nada";
					Reg.scoreAdd4 = 0;
				}
				else 
					estado = "waiting";
			case "waiting":
				timeToRoll -= FlxG.elapsed;
				if (timeToRoll < 0 ) 
				{ 
					
					currentTeam.multiplier = 1;
					if (currentTeam.carcel == 1)
					{
						currentTeam.carcel = 0;
						timeToRoll = 0.5; 	
						if (currentTeam == team4)
							estado = "ruleta";
						else
							estado = "waiting"; 
						if (currentTeam == team1)
							currentTeam = team2;
						else if (currentTeam == team2)
							currentTeam = team3;
						else if (currentTeam == team3)
							currentTeam = team4;
						else
							currentTeam = team1;
					}
					else
					{
						dice.roll(); 
						estado = "rolling";
					}
				} 
			case "rolling":
				if (!dice.rolling) 
				{ 
					estado = "moving"; 
					movesLeft = dice.value(); 
					moveTeam(null); 
					passGo = false;
				}
			case "moving":
				if (casilleros[currentTeam.position]._tipo == "Salida" && !passGo)
				{
					passGo = true;
					currentTeam.addScore(20);
					scoreText.color = FlxColor.GREEN;
					scoreText.text = "+" + Std.string(20);
					scoreText.alpha = 1;
					scoreText.x = currentTeam.scoreText.x;
					scoreText.y = currentTeam.scoreText.y;
					var tween = FlxTween.tween(scoreText, { y:scoreText.y - 50, alpha:0 }, 0.5 );	
				}
				if (movesLeft == -1) 
				{ 
					switch(casilleros[currentTeam.position]._tipo)
					{
						case "Verde":
							currentTeam.addScore(3);
							scoreText.color = FlxColor.GREEN;
							scoreText.text = "+3";
							scoreText.alpha = 1;
							scoreText.x = currentTeam.scoreText.x;
							scoreText.y = currentTeam.scoreText.y;
							var tween = FlxTween.tween(scoreText,{y:scoreText.y-50,alpha:0},0.5);
						case "Rojo":
							if (currentTeam.score > 0)
							{
								scoreText.color = FlxColor.RED;
								scoreText.text = "-3";
								scoreText.alpha = 1;
								scoreText.x = currentTeam.scoreText.x;
								scoreText.y = currentTeam.scoreText.y;
								var tween = FlxTween.tween(scoreText,{y:scoreText.y-50,alpha:0},0.5);
							}
							currentTeam.addScore( -3);
						case "MultX2":
							currentTeam.multiplier = 2;
						case "Carcel":
							currentTeam.carcel = 1;
						case "Dado":
							estado = "waiting";
							return;

							
					}
					timeToRoll = 0.5; 	
					if (currentTeam == team4)
						estado = "ruleta";
					else
						estado = "waiting"; 
					if (currentTeam == team1)
						currentTeam = team2;
					else if (currentTeam == team2)
						currentTeam = team3;
					else if (currentTeam == team3)
						currentTeam = team4;
					else
						currentTeam = team1;
				}
			case "ruleta":
				timeToSpin -= FlxG.elapsed;
				if (timeToSpin < 0 )
				{	
					ruletaSound.play();
					ruletaSound.fadeIn();
					var tween = FlxTween.tween(ruleta.disc.scale, { x:1.2, y:1.2 }, 0.8, { type:FlxTween.ONESHOT, ease:FlxEase.bounceOut } );
					var tween = FlxTween.tween(ruleta.arrow.scale, { x:1.2, y:1.2 }, 0.8, { type:FlxTween.ONESHOT, ease:FlxEase.bounceOut } );
					ruleta.spin();
					estado = "spinning";
				}
			case "spinning":
				spinTime -= FlxG.elapsed;
				if (spinTime < 1)
					ruletaSound.fadeOut(1);
				if (ruleta.getMode() != -1)
				{
					ruletaFinSound.play();
					estado = "modename";
					trace("Resultado: " + Std.string(ruleta.getMode()));
				}
			case "modename":
				switch(ruleta.getMode())
				{
					case 1:
						modeName.text = "EL RELOJ MIENTE";
					case 2:
						modeName.text = "ULTIMO EN CONTESTAR";
					case 3:
						modeName.text = "MEZCLA";
					case 4:
						modeName.text = "PRIMERO EN CONTESTAR";
					case 5:
						modeName.text = "MEMORIA";
					case 6:
						modeName.text = "MIENTRAS ANTES MEJOR";
					case 7:
						modeName.text = "ALREVES";
				}
				var tween = FlxTween.tween(modeName.scale, { x:1, y:1 }, 0.8, { type:FlxTween.ONESHOT, ease:FlxEase.bounceOut, complete:fade } );
				estado = "nada";
			case "fading":
				timeToFade -= FlxG.elapsed;
				Reg.score1 = team1.score;
				Reg.score2 = team2.score;
				Reg.score3 = team3.score;
				Reg.score4 = team4.score;
				Reg.multiplier1 = team1.multiplier;
				Reg.multiplier2 = team2.multiplier;
				Reg.multiplier3 = team3.multiplier;
				Reg.multiplier4 = team4.multiplier;
				Reg.position1 = team1.position;
				Reg.position2 = team2.position;
				Reg.position3 = team3.position;
				Reg.position4 = team4.position;
				Reg.angle = ruleta.disc.angle;
				Reg.carcel1 = team1.carcel;
				Reg.carcel2 = team2.carcel;
				Reg.carcel3 = team3.carcel;
				Reg.carcel4 = team4.carcel;
				if (timeToFade < 0)
				{
					FlxG.camera.fade(FlxColor.BLACK,1,false,onFade);
					estado = "nada";
				}
		}
		var gamePad = FlxG.gamepads.getActiveGamepads()[0];
		if (gamePad != null && gamePad.justPressed(LogitechButtonID.FOUR))
			trace("WAKA");
		
	}	
	
	private function fade(tween:FlxTween):Void
	{
		estado = "fading";
	}
	
	private function onFade():Void
	{
		Reg.modo = modeName.text;
		switch(ruleta.getMode())
		{
			case 1:
				FlxG.switchState(new RelojMienteState());
			case 2:
				FlxG.switchState(new UltimoState());
			case 3:
				FlxG.switchState(new MezclaState());
			case 4:
				FlxG.switchState(new PrimeroState());
			case 5:
				FlxG.switchState(new MemoriaState());
			case 6:
				FlxG.switchState(new AntesMejorState());
			case 7:
				FlxG.switchState(new AlrevezState());
		}
		
	}
	
	private function moveTeam(tween:FlxTween):Void
	{
		if (movesLeft == 0)
		{
			movesLeft--;
			return;
		}
		if (fichaSound.playing)
			fichaSound.stop();
		fichaSound.play();
		var duration:Float = 0.5;
		if (0 <= currentTeam.position && currentTeam.position < 6)
			var tween = FlxTween.quadMotion(currentTeam, currentTeam.x, currentTeam.y, currentTeam.x + 100 * 0.5, currentTeam.y - 100, currentTeam.x + 100, currentTeam.y, duration, true, {type:FlxTween.ONESHOT ,complete:moveTeam} );
		else if (6 <= currentTeam.position && currentTeam.position < 10)
			var tween = FlxTween.quadMotion(currentTeam, currentTeam.x, currentTeam.y, currentTeam.x+100, currentTeam.y + 100 * 0.5, currentTeam.x, currentTeam.y + 100, duration, true, { type:FlxTween.ONESHOT ,complete:moveTeam} );
		else if (10 <= currentTeam.position && currentTeam.position < 16)
			var tween = FlxTween.quadMotion(currentTeam, currentTeam.x, currentTeam.y, currentTeam.x - 100 * 0.5, currentTeam.y + 100, currentTeam.x - 100, currentTeam.y, duration, true, { type:FlxTween.ONESHOT ,complete:moveTeam} );
		else
			var tween = FlxTween.quadMotion(currentTeam, currentTeam.x, currentTeam.y, currentTeam.x -100, currentTeam.y - 100 * 0.5, currentTeam.x, currentTeam.y - 100, duration, true, { type:FlxTween.ONESHOT ,complete:moveTeam} );
		if (currentTeam.position < 19)
			currentTeam.position++;
		else
			currentTeam.position = 0;		
		movesLeft--;
	}
}